package com.hmusic.mymusic.service.impl;

import com.hmusic.mymusic.dao.ConsumerMapper;
import com.hmusic.mymusic.domain.Consumer;
import com.hmusic.mymusic.service.ConsumerService;
import com.hmusic.mymusic.service.MsmService;
import com.hmusic.mymusic.utils.CodeUtil;
import com.hmusic.mymusic.utils.DateUtil;
import com.hmusic.mymusic.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

/**
 * 用户service接口实现类
 */
@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Autowired
    private ConsumerMapper consumerMapper;
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${avatorImages.dir}")
    private String realPath;

    /**
     * 添加用户
     *
     * @param consumer
     */
    @Override
    public void insert(Consumer consumer) {
        try{
            Consumer consumer1 = consumerMapper.oneConsumerByName(consumer.getUsername());
            Consumer consumer2 = consumerMapper.oneConsumerByPhone(consumer.getPhone_num());
            Consumer consumer3 = consumerMapper.oneConsumerByEmail(consumer.getEmail());
            if (consumer1 != null){
                throw new RuntimeException("用户名已存在");
            }
            if (consumer2 != null){
                throw new RuntimeException("电话已注册");
            }
            if (consumer3 != null){
                throw new RuntimeException("邮箱已注册");
            } else {
                if (consumer.getSex() == null || consumer.getSex() == ""){
                    consumer.setSex("2");
                }
                if (consumer.getSex().equals("1")){
                    consumer.setAvator("/img/avatorImages/userAvator1.jpeg");
                }
                if (consumer.getSex().equals("0")){
                    consumer.setAvator("/img/avatorImages/userAvator0.jpeg");
                }
                if (consumer.getSex().equals("2")) {
                    consumer.setAvator("/img/avatorImages/userAvator2.jpeg");
                }
                consumer.setCreate_time(DateUtil.getDate());
                consumer.setUpdate_time(DateUtil.getDate());
            }

            consumerMapper.insert(consumer);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 用户注册（用户）
     *
     * @param consumer
     */
    @Override
    public void register(Consumer consumer) {
        try{
            Consumer consumer1 = consumerMapper.oneConsumerByName(consumer.getUsername());
            Consumer consumer3 = consumerMapper.oneConsumerByEmail(consumer.getEmail());
            if (consumer1 != null){
                throw new RuntimeException("用户名已存在");
            }
            if (consumer3 != null){
                throw new RuntimeException("邮箱已注册");
            } else {
                if (consumer.getSex() == null || consumer.getSex() == ""){
                    consumer.setSex("2");
                }
                if (consumer.getSex().equals("1")){
                    consumer.setAvator("/img/avatorImages/userAvator1.jpeg");
                }
                if (consumer.getSex().equals("0")){
                    consumer.setAvator("/img/avatorImages/userAvator0.jpeg");
                }
                if (consumer.getSex().equals("2")) {
                    consumer.setAvator("/img/avatorImages/userAvator2.jpeg");
                }
                int checkCode = checkCode(consumer);
                System.out.println(checkCode);
                if (checkCode == 1){
                    throw new RuntimeException("验证码不正确");
                }
                if (checkCode == 2){
                    throw new RuntimeException("请输入验证码");
                }
                consumer.setCreate_time(DateUtil.getDate());
                consumer.setUpdate_time(DateUtil.getDate());
            }
            consumerMapper.insert(consumer);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 验证验证码是否正确
     * @param consumer
     * @return
     */
    public int checkCode(Consumer consumer){
        System.out.println(consumer.getCode());
        String getCode = (String) redisUtil.get(consumer.getEmail());
        System.out.println(getCode);
        if (getCode!=null){
            if (getCode.equals(consumer.getCode())){
                return 0;
            }else {
                return 1;
            }
        }else {
            return 2;
        }
    }

    /**
     * 根据邮箱查询一个用户（判断登录）
     *
     * @param consumer
     */
    @Override
    public Consumer oneConsumerByEmail(Consumer consumer) {
        try{
            Consumer consumer1 = consumerMapper.oneConsumerByEmail(consumer.getEmail());
            if (consumer1 == null){
                throw new RuntimeException("邮箱或密码错误!");
            }else{
                if (consumer1.getPassword().equals(consumer.getPassword())){
                    return consumer1;
                }else {
                    throw new RuntimeException("账号或密码错误!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 根据邮箱查询一个用户（发送验证码之前）
     *
     * @param email
     */
    @Override
    public Consumer oneConsumerByEmailCode(String email) {
        return consumerMapper.oneConsumerByEmail(email);
    }

    /**
     * 计算用户数量
     */
    @Override
    public int consumerCount() {
        return consumerMapper.consumerCount();
    }

    /**
     * 计算各个性别的用户数量
     *
     * @param sex
     */
    @Override
    public int consumerSexCount(String sex) {
        return consumerMapper.consumerSexCount(sex);
    }

    /**
     * 修改用户
     *
     * @param consumer
     */
    @Override
    public void update(Consumer consumer) {
        try{
            int flag = isUpdate(consumer);
            if (flag == 0){
                consumer.setUpdate_time(DateUtil.getDate());
                consumerMapper.update(consumer);
            }
            if (flag == 1){
                throw new RuntimeException("用户名已存在");
            }
            if (flag == 2){
                throw new RuntimeException("手机号已被注册");
            }
            if (flag == 3){
                throw new RuntimeException("邮箱已被注册");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 判断用户信息是否可以被修改
     * @param consumer
     * @return
     */
    public int isUpdate(Consumer consumer){
        String id = consumer.getId();
        Consumer consumer1 = consumerMapper.oneConsumerByName(consumer.getUsername());
        Consumer consumer2 = consumerMapper.oneConsumerByPhone(consumer.getPhone_num());
        Consumer consumer3 = consumerMapper.oneConsumerByEmail(consumer.getEmail());
        if (consumer1 == null && consumer2 == null && consumer3 == null){
            return 0;
        }else {
            if (consumer1 != null && !consumer1.getId().equals(id)){
                return 1;
            }
            if (consumer2 != null && !consumer2.getId().equals(id)){
                return 2;
            }
            if (consumer3 != null && !consumer3.getId().equals(id)){
                return 3;
            }
        }
        return 0;
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    public void delete(String id) {
        try{
            Consumer consumer = consumerMapper.selectByPrimaryKey(id);
            String oldConsumerAvatorUrl = consumer.getAvator();
            String newConsumerAvatorUrl = oldConsumerAvatorUrl.substring(18);
            if (!newConsumerAvatorUrl.equals("userAvator0.jpeg")&&
                    !newConsumerAvatorUrl.equals("userAvator1.jpeg")&&
                    !newConsumerAvatorUrl.equals("userAvator2.jpeg")){
                File file=new File(realPath,newConsumerAvatorUrl);
                if(file.exists())file.delete();//删除原有头像地址
            }
            consumerMapper.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据主键查询整个对象
     *
     * @param id
     */
    @Override
    public Consumer selectByPrimaryKey(String id) {
        return consumerMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询所有用户
     */
    @Override
    public List<Consumer> allConsumer() {
        return consumerMapper.allConsumer();
    }

    /**
     * 根据用户名模糊查询
     *
     * @param username
     */
    @Override
    public List<Consumer> selectByUserName(String username) {
        return consumerMapper.selectByUserName(username);
    }


}
